<template>
  <div class="chapter-management-page">
    <div class="page-header">
      <h2 class="page-title">章节管理</h2>
      <div class="action-buttons">
        <el-button type="primary" @click="openAddChapterDialog">
          <i class="el-icon-plus"></i> 新增章节
        </el-button>
      </div>
    </div>

    <div class="course-selector">
      <el-form :model="courseForm" label-width="80px">
        <el-form-item label="选择课程">
          <el-select v-model="selectedCourseID" placeholder="请选择课程" style="width: 200px" @change="fetchChapters">
            <el-option v-for="course in courseList" :key="course.courseID" :label="course.name" :value="course.courseID" />
          </el-select>
        </el-form-item>
      </el-form>
    </div>

    <div class="chapter-list-container">
      <div v-if="!selectedCourseID" class="empty-tip">请先选择课程</div>
      <div v-else-if="chapterList.length === 0" class="empty-tip">该课程暂无章节</div>
      <el-tree
          v-else
          :data="chapterList"
          :props="chapterProps"
          show-checkbox
          node-key="chapterID"
          class="chapter-tree"
          @node-click="handleNodeClick">
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <span>{{ node.label }}</span>
            <span class="action-buttons">
              <el-button size="small" @click.stop="openEditChapterDialog(data)">编辑</el-button>
              <el-button size="small" type="danger" @click.stop="handleDeleteChapter(data.chapterID)">删除</el-button>
            </span>
          </span>
        </template>
      </el-tree>
    </div>

    <!-- 新增/编辑章节对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="400px"
        @open="onDialogOpen"
        @close="onDialogClose"
        :append-to-body="true">

      <template #default>
        <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px">
          <el-form-item label="章节名称" prop="name">
            <el-input v-model="formData.name"></el-input>
          </el-form-item>
          <el-form-item label="章节顺序" prop="order">
            <el-input-number v-model="formData.order" min="1"></el-input-number>
          </el-form-item>
          <el-form-item label="父章节" prop="parentChapterID">
            <el-select v-model="formData.parentChapterID" placeholder="选择父章节" style="width: 100%">
              <el-option label="根章节" :value="null"></el-option>
              <el-option
                  v-for="chapter in parentChapters"
                  :key="chapter.chapterID"
                  :label="getChapterPath(chapter)"
                  :value="chapter.chapterID">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </template>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="validateAndSave">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, nextTick } from 'vue';
import { ElTree, ElDialog, ElForm, ElFormItem, ElInput, ElInputNumber, ElSelect, ElOption, ElMessage, ElMessageBox } from 'element-plus';
import { getCourseList, getCourseChapters, addCourseChapter } from '@/api/course.js';

export default {
  components: {
    ElTree,
    ElDialog,
    ElForm,
    ElFormItem,
    ElInput,
    ElInputNumber,
    ElSelect,
    ElOption,
    ElMessage,
    ElMessageBox
  },
  setup() {
    const courseList = ref([]);
    const selectedCourseID = ref(null);
    const chapterList = ref([]);
    const dialogVisible = ref(false);
    const formData = ref({
      courseID: null,
      name: '',
      order: 1,
      parentChapterID: null
    });
    const dialogTitle = ref('新增章节');
    const isEditMode = ref(false);
    const formRef = ref(null);
    const currentEditingChapter = ref(null);
    const parentChapters = ref([]);

    // 表单验证规则
    const formRules = {
      name: [
        { required: true, message: '请输入章节名称', trigger: 'blur' }
      ],
      order: [
        { required: true, message: '请输入章节顺序', trigger: 'blur' },
        { type: 'number', message: '顺序必须为数字值', trigger: 'blur' }
      ]
    };

    // 树状结构配置
    const chapterProps = {
      children: 'children',
      label: 'name'
    };

    // 获取课程列表
    const fetchCourseList = async () => {
      try {
        // 这里假设使用之前课程管理中的API
        const res = await getCourseList({ page: 1, pageSize: 100 });

        if (res.code === 1) {
          courseList.value = res.data.items;
          if (res.data.items.length > 0) {
            selectedCourseID.value = res.data.items[0].courseID;
            fetchChapters();
          }
        } else {
          console.error('获取课程列表失败：', res.message);
          ElMessage.error(res.message || '获取课程列表失败');
        }
      } catch (error) {
        console.error('请求课程列表出错：', error);
        ElMessage.error('网络错误，请稍后重试');
      }
    };

    // 获取课程章节
    const fetchChapters = async () => {
      if (!selectedCourseID.value) return;

      try {
        const res = await getCourseChapters(selectedCourseID.value);

        if (res.code === 1) {
          // 转换为树状结构
          transformToTree(res.data.chapters);
          formData.value.courseID = selectedCourseID.value;
        } else {
          console.error('获取章节列表失败：', res.message);
          ElMessage.error(res.message || '获取章节列表失败');
        }
      } catch (error) {
        console.error('请求章节列表出错：', error);
        ElMessage.error('网络错误，请稍后重试');
      }
    };

    // 转换为树状结构
    const transformToTree = (chapters) => {
      const map = {};
      const roots = [];

      // 创建节点映射
      chapters.forEach(chapter => {
        map[chapter.chapterID] = { ...chapter, children: [] };
      });

      // 构建树状结构
      chapters.forEach(chapter => {
        const node = map[chapter.chapterID];
        if (chapter.parentID === null) {
          roots.push(node);
        } else {
          if (map[chapter.parentID]) {
            map[chapter.parentID].children.push(node);
          } else {
            // 父节点不存在，作为根节点处理
            roots.push(node);
          }
        }
      });

      chapterList.value = roots;
      updateParentChapters();
    };

    // 更新父章节列表
    const updateParentChapters = () => {
      // 扁平化处理，获取所有可作为父节点的章节
      const flatChapters = [];

      const flatten = (chapters) => {
        chapters.forEach(chapter => {
          flatChapters.push(chapter);
          if (chapter.children && chapter.children.length > 0) {
            flatten(chapter.children);
          }
        });
      };

      flatten(chapterList.value);
      parentChapters.value = flatChapters;
    };

    // 获取章节路径（用于显示层级关系）
    const getChapterPath = (chapter) => {
      if (!chapter.parentID) return chapter.name;

      let path = chapter.name;
      let currentParentID = chapter.parentID;

      while (currentParentID) {
        const parent = findChapterById(currentParentID);
        if (parent) {
          path = parent.name + ' > ' + path;
          currentParentID = parent.parentID;
        } else {
          break;
        }
      }

      return path;
    };

    // 根据ID查找章节
    const findChapterById = (id) => {
      const flatten = (chapters) => {
        for (const chapter of chapters) {
          if (chapter.chapterID === id) return chapter;
          if (chapter.children && chapter.children.length > 0) {
            const result = flatten(chapter.children);
            if (result) return result;
          }
        }
        return null;
      };

      return flatten(chapterList.value);
    };

    // 打开新增章节对话框
    const openAddChapterDialog = () => {
      if (!selectedCourseID.value) {
        ElMessage.warning('请先选择课程');
        return;
      }

      dialogTitle.value = '新增章节';
      isEditMode.value = false;
      formData.value = {
        courseID: selectedCourseID.value,
        name: '',
        order: 1,
        parentChapterID: null
      };

      nextTick(() => {
        if (formRef.value) {
          formRef.value.resetFields();
        }
      });

      dialogVisible.value = true;
    };

    // 打开编辑章节对话框
    const openEditChapterDialog = (chapter) => {
      dialogTitle.value = '编辑章节';
      isEditMode.value = true;
      currentEditingChapter.value = chapter;
      formData.value = {
        courseID: selectedCourseID.value,
        name: chapter.name,
        order: chapter.order,
        parentChapterID: chapter.parentID
      };

      nextTick(() => {
        if (formRef.value) {
          formRef.value.resetFields();
        }
      });

      dialogVisible.value = true;
    };

    // 对话框打开回调
    const onDialogOpen = () => {
      console.log('对话框已打开');
    };

    // 对话框关闭回调
    const onDialogClose = () => {
      console.log('对话框已关闭');
    };

    // 验证并保存章节
    const validateAndSave = () => {
      if (!formRef.value) return;

      formRef.value.validate((valid) => {
        if (valid) {
          handleSaveChapter();
        } else {
          console.error('表单验证失败');
          ElMessage.error('请填写所有必填字段');
          return false;
        }
      });
    };

    // 保存章节（新增/编辑）
    const handleSaveChapter = async () => {
      try {
        let res;

        if (isEditMode.value && currentEditingChapter.value) {
          // 编辑章节逻辑（这里需要编辑接口）
          ElMessage.warning('编辑功能暂未实现');
        } else {
          // 新增章节
          res = await addCourseChapter({
            courseID: formData.value.courseID,
            name: formData.value.name,
            order: formData.value.order,
            parentChapterID: formData.value.parentChapterID
          });
        }

        if (res && res.code === 1) {
          dialogVisible.value = false;
          fetchChapters();
          ElMessage.success(isEditMode.value ? '章节更新成功' : '章节新增成功');
        } else {
          console.error(isEditMode.value ? '章节更新失败' : '章节新增失败：', res ? res.message : '未知错误');
          ElMessage.error(res ? res.message : (isEditMode.value ? '章节更新失败' : '章节新增失败'));
        }
      } catch (error) {
        console.error('请求出错：', error);
        ElMessage.error('网络错误，请稍后重试');
      }
    };

    // 删除章节（需要删除接口）
    const handleDeleteChapter = (chapterID) => {
      ElMessageBox.confirm(
          '确定要删除此章节吗？删除后将无法恢复。',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
      ).then(() => {
        // 删除逻辑（需要删除接口）
        ElMessage.warning('删除功能暂未实现');
      }).catch(() => {
        // 取消操作
      });
    };

    // 节点点击事件
    const handleNodeClick = (data) => {
      console.log('点击节点', data);
    };

    onMounted(() => {
      fetchCourseList();
    });

    return {
      courseList,
      selectedCourseID,
      chapterList,
      dialogVisible,
      formData,
      dialogTitle,
      isEditMode,
      formRef,
      formRules,
      chapterProps,
      parentChapters,
      fetchCourseList,
      fetchChapters,
      openAddChapterDialog,
      openEditChapterDialog,
      onDialogOpen,
      onDialogClose,
      validateAndSave,
      handleSaveChapter,
      handleDeleteChapter,
      handleNodeClick,
      getChapterPath
    };
  }
};
</script>

<style scoped>
/* 样式保持与课程管理页面一致 */
.chapter-management-page {
  padding: 20px;
  height: calc(100vh - 60px);
  display: flex;
  flex-direction: column;
}

.page-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.course-selector {
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  padding: 15px;
}

.chapter-list-container {
  flex: 1;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  padding: 20px;
  overflow-y: auto;
}

.empty-tip {
  text-align: center;
  color: #909399;
  padding: 40px 0;
}

.chapter-tree {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.custom-tree-node {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.action-buttons {
  margin-left: 10px;
}
</style>